<template>
  <div class="nav-bar">
    <van-icon @click="toHome" name="wap-home-o" size="0.5rem" />
    <form action="/">
      <van-search
        v-model="searchkey"
        shape="round"
        show-action
        @search="search"
        placeholder="请输入搜索关键词"
      >
      <template #action>
        <div @click="search">搜索</div>
      </template>
      </van-search>
    </form>
    <van-icon @click="toUser" name="friends-o" size="0.5rem"/>
    <div class="nav-bar-box" v-if="showBox">
      <div class="item" @click="toDetail(item.id)" v-for="item in list" :key="item.id">
        {{item.goodsName}} <span class="enter">进入</span>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  name: 'NavBar',
  data() {
    return {
      searchkey: '',
      list: []
    }
  },
  computed: {
    showBox() {
      return this.searchkey && this.list.length
    }
  },
  watch: {
    searchkey(val) {
      if (!val) {
        this.list.length = 0
      }
    }
  },
  methods: {
    /**
     * 导航到首页
     */
    toHome() {
      this.$router.push({
        path: '/home'
      })
    },
    /**
     * 导航到个人中心
     */
    toUser() {
      this.$router.push({
        path: '/user'
      })
    },
    /**
     * 搜索关键词
     */
    search() {
      const query = {
        goodsName: this.searchkey,
        pageNum: 1,
        pageSize: -1
      }
      this.$api.shop.getAllGoods(query).then(res => {
        if (res.code === 200) {
          this.list = res.data.records
        }
      })
    },
    /**
     * 进入食品详情
     */
    toDetail(id) {
      this.$router.push('/goods-detail/' + id)
    }
  }
}
</script>
<style lang="less" scoped>
.nav-bar{
  position: fixed;
  width: 100%;
  top: 0;
  left: 0;
  background-color: #fff;
  display: flex;
  flex-flow: row nowrap;
  justify-content: space-around;
  align-items: center;
  z-index: 1;
  .nav-bar-box {
    position: absolute;
    width: 100%;
    // height: 90px;
    max-height: 90px;
    overflow-y: auto;
    box-sizing: border-box;
    padding-left: 60px;
    opacity: .8;
    top: 50px;
    background-color: lightgray;
    .item{
      padding: 5px 0;
      border-bottom: 1px solid lightgray;
      height: 30px;
      line-height: 30px;
      color: brown;
      .enter{
        text-decoration:underline;
        color: #fff;
        margin-left: 10px;
      }
    }
  }
}
</style>
